package com.doubao.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doubao.chat.entity.ChatMessage;
import com.doubao.chat.entity.ChatSession;
import com.doubao.chat.mapper.ChatMessageMapper;
import com.doubao.chat.mapper.ChatSessionMapper;
import com.doubao.chat.service.AIProviderService;
import com.doubao.chat.service.ChatService;
import com.doubao.common.result.Result;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.service.SmartDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class ChatServiceImpl implements ChatService {

    private final ChatSessionMapper sessionMapper;
    private final ChatMessageMapper messageMapper;
    private final SmartDeviceService deviceService;

    // 注入原始的AIProviderService实现
    private final AIProviderService aiProviderService;

    // 注入Coze SDK的AIProviderService实现
    private final AIProviderService cozeSDKProviderService;

    @Value("${chat.context-message-limit:10}")
    private int contextMessageLimit;

    @Value("${chat.session-reuse-hours:24}")
    private int sessionReuseHours;

    @Autowired
    public ChatServiceImpl(
            ChatSessionMapper sessionMapper,
            ChatMessageMapper messageMapper,
            SmartDeviceService deviceService,
            @Qualifier("AIProviderServiceImpl") AIProviderService aiProviderService,
            @Qualifier("CozeSDKProviderServiceImpl") AIProviderService cozeSDKProviderService) {
        this.sessionMapper = sessionMapper;
        this.messageMapper = messageMapper;
        this.deviceService = deviceService;
        this.aiProviderService = aiProviderService;
        this.cozeSDKProviderService = cozeSDKProviderService;
    }

    @Override
    @Transactional
    public Result<String> processMessage(Long userId, Long deviceId, String content) {
        try {
            // 查找现有会话，如果没有则创建新会话
            ChatSession session = findOrCreateSession(userId, deviceId);

            // 保存用户消息
            ChatMessage userMessage = new ChatMessage();
            userMessage.setUuid(UUID.randomUUID().toString());
            userMessage.setSessionId(session.getId());
            userMessage.setUserId(userId);
            userMessage.setDeviceId(deviceId);
            userMessage.setRole("user");
            userMessage.setContent(content);
            userMessage.setStorageType("db");
            userMessage.setMessageHash(calculateHash(content));
            userMessage.setCreatedAt(LocalDateTime.now());
            userMessage.setUpdatedAt(LocalDateTime.now());
            messageMapper.insert(userMessage);

            // 获取会话上下文消息
            List<ChatMessage> contextMessages = getContextMessages(session.getId());

            // 获取设备信息
            SmartDevice device = deviceService.getById(deviceId);
            if (device == null) {
                return Result.failed("设备不存在");
            }

            // 根据提供商类型选择使用的服务
            Result<String> systemPromptResult;
            Result<String> aiResponse;

            if (device.getAiProviderId() == 4) { // 扣子AI
                // 使用Coze SDK实现
                systemPromptResult = cozeSDKProviderService.getSystemPrompt(deviceId);
                String systemPrompt = systemPromptResult.isSuccess() ? systemPromptResult.getData() : "";

                aiResponse = cozeSDKProviderService.sendMessageToProvider(
                        deviceId, systemPrompt, contextMessages, content);
            } else {
                // 使用原始实现
                systemPromptResult = aiProviderService.getSystemPrompt(deviceId);
                String systemPrompt = systemPromptResult.isSuccess() ? systemPromptResult.getData() : "";

                aiResponse = aiProviderService.sendMessageToProvider(
                        deviceId, systemPrompt, contextMessages, content);
            }

            if (aiResponse.isSuccess()) {
                // 保存AI回复
                ChatMessage assistantMessage = new ChatMessage();
                assistantMessage.setUuid(UUID.randomUUID().toString());
                assistantMessage.setSessionId(session.getId());
                assistantMessage.setUserId(userId);
                assistantMessage.setDeviceId(deviceId);
                assistantMessage.setRole("assistant");
                assistantMessage.setContent(aiResponse.getData());
                assistantMessage.setAiProviderId(device.getAiProviderId());
                assistantMessage.setAiModelId(device.getAiModelId());
                assistantMessage.setStorageType("db");
                assistantMessage.setMessageHash(calculateHash(aiResponse.getData()));
                assistantMessage.setCreatedAt(LocalDateTime.now());
                assistantMessage.setUpdatedAt(LocalDateTime.now());
                messageMapper.insert(assistantMessage);

                // 更新会话信息
                session.setMessageCount(session.getMessageCount() + 2); // 增加用户消息和AI回复
                session.setLastMessageTime(LocalDateTime.now());
                session.setUpdatedAt(LocalDateTime.now());
                sessionMapper.updateById(session);

                // 增加设备使用次数
                deviceService.increaseUsageCount(deviceId);
            }

            return aiResponse;
        } catch (Exception e) {
            log.error("处理消息异常", e);
            return Result.failed("处理消息异常: " + e.getMessage());
        }
    }

    /**
     * 查找或创建会话
     * 优化会话管理逻辑，优先复用现有会话
     */
    private ChatSession findOrCreateSession(Long userId, Long deviceId) {
        // 查找最近的活跃会话，按最后消息时间降序排序
        LambdaQueryWrapper<ChatSession> queryWrapper = new LambdaQueryWrapper<ChatSession>()
                .eq(ChatSession::getUserId, userId)
                .eq(ChatSession::getDeviceId, deviceId)
                .eq(ChatSession::getStatus, 1)  // 正常状态
                .orderByDesc(ChatSession::getLastMessageTime)
                .last("LIMIT 1");

        ChatSession existingSession = sessionMapper.selectOne(queryWrapper);

        if (existingSession != null) {
            // 检查会话是否在指定时间内有活动，如果有则复用
            if (existingSession.getLastMessageTime() != null &&
                    existingSession.getLastMessageTime().isAfter(LocalDateTime.now().minusHours(sessionReuseHours))) {
                log.info("复用现有会话: {}", existingSession.getId());
                return existingSession;
            }
        }

        // 创建新会话
        SmartDevice device = deviceService.getById(deviceId);
        String title = "与" + (device != null ? device.getName() : "智能体") + "的对话";

        ChatSession newSession = new ChatSession();
        newSession.setUserId(userId);
        newSession.setDeviceId(deviceId);
        newSession.setTitle(title);
        newSession.setMessageCount(0);
        newSession.setLastMessageTime(LocalDateTime.now());
        newSession.setStatus(1); // 活跃状态
        newSession.setCreatedAt(LocalDateTime.now());
        newSession.setUpdatedAt(LocalDateTime.now());
        sessionMapper.insert(newSession);

        log.info("创建新会话: {}", newSession.getId());
        return newSession;
    }

    /**
     * 获取会话上下文消息
     */
    private List<ChatMessage> getContextMessages(Long sessionId) {
        // 获取最近的N条消息作为上下文，按创建时间升序排列
        List<ChatMessage> messages = messageMapper.selectContextMessages(sessionId, contextMessageLimit);

        if (messages == null) {
            return Collections.emptyList();
        }

        return messages;
    }

    /**
     * 计算消息哈希值
     */
    private String calculateHash(String content) {
        return DigestUtils.md5DigestAsHex(content.getBytes(StandardCharsets.UTF_8));
    }
}